import React, { Component } from 'react';
import { Form, Input, Button, Row, Col, message, DatePicker, Icon, Modal } from 'antd';
import { connect } from 'dva';
import getFileId from '@/utils/getFileId';
import { OssUpload, UploadImageSample } from 'scd';
const FormItem = Form.Item;
const { RangePicker } = DatePicker;

@Form.create()
@connect(({ loading }) => ({
  loading: !!loading.effects['user/sendAuthentication'],
}))
class Authentication extends Component {
  state = {
    confirmDirty: false,
    modalVisible: false,
  };

  handleSubmit = e => {
    e.preventDefault();
    const { form, dispatch } = this.props;
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        let values = {
          ...fieldsValue,
          validStartTime: fieldsValue.validTime[0].format('YYYY-MM-DD HH:mm'),
          validEndTime: fieldsValue.validTime[1].format('YYYY-MM-DD HH:mm'),
          picFrontId: getFileId(fieldsValue.picFrontId),
          picBackId: getFileId(fieldsValue.picBackId),
        };
        dispatch({
          type: 'user/sendAuthentication',
          payload: values,
        })
          .then(() => {
            message.success('申请审核成功');
            dispatch({
              type: 'user/getUserInfo',
            });
            this.toggleVisible();
          })
          .catch(errMsg => {
            message.error(errMsg);
          });
      }
    });
  };
  normFile = e => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  toggleVisible = () => {
    this.setState(({ modalVisible }) => ({
      modalVisible: !modalVisible,
    }));
  };

  render() {
    const { modalVisible } = this.state;
    const {
      form: { getFieldDecorator, getFieldValue },
      loading,
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };

    const rangeConfig = {
      rules: [{ type: 'array', required: true, message: '请选择证件有效期' }],
    };
    const uploadButton = text => (
      <span>
        <Icon type="plus" />
        <span className="ant-upload-text">{text}</span>
      </span>
    );
    return (
      <>
        <Button onClick={this.toggleVisible}>实名认证</Button>
        <Modal
          title="实名认证"
          visible={modalVisible}
          destroyOnClose
          maskClosable={false}
          confirmLoading={loading}
          width={600}
          cancelText="取消"
          okText="确定"
          onOk={this.handleSubmit}
          onCancel={this.toggleVisible}
        >
          <Form onSubmit={this.handleSubmit}>
            <Row>
              <Col span={24}>
                <FormItem label="姓名" {...formItemLayout}>
                  {getFieldDecorator('name', {
                    rules: [
                      {
                        required: true,
                        message: '请输入姓名',
                      },
                    ],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <FormItem label="身份证号" {...formItemLayout}>
                  {getFieldDecorator('idCard', {
                    rules: [
                      {
                        required: true,
                        message: '请输入姓名',
                      },
                    ],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <FormItem label="证件有效期" {...formItemLayout}>
                  {getFieldDecorator('validTime', rangeConfig)(
                    <RangePicker placeholder={['起始时间', '结束时间']} />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label="上传证件">
                  支持.png .pdf .jpg格式上传，大小5m以内.
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col offset={4} span={20}>
                <Col span={6}>
                  <FormItem>
                    {getFieldDecorator('picFrontId', {
                      valuePropName: 'fileList',
                      getValueFromEvent: this.normFile,
                      initialValue: [],
                    })(
                      <OssUpload
                        listType="picture-card"
                        data={{
                          businessId: 0,
                          businessType: 'string',
                          companyId: 0,
                          digestMethod: 1,
                          ext: '',
                          moduleCode: 'company',
                          productLineId: 0,
                          userId: 1,
                        }}
                      >
                        {getFieldValue('picFrontId') && getFieldValue('picFrontId').length === 1
                          ? null
                          : uploadButton('上传证件正面')}
                      </OssUpload>
                    )}
                  </FormItem>
                </Col>
                <Col span={6}>
                  <UploadImageSample />
                </Col>
                <Col span={6}>
                  <FormItem>
                    {getFieldDecorator('picBackId', {
                      valuePropName: 'fileList',
                      getValueFromEvent: this.normFile,
                      rules: [
                        {
                          required: true,
                          message: '请上传',
                        },
                      ],
                    })(
                      <OssUpload
                        listType="picture-card"
                        data={{
                          businessId: 0,
                          businessType: 'string',
                          companyId: 0,
                          digestMethod: 1,
                          ext: '',
                          moduleCode: 'company',
                          productLineId: 0,
                          userId: 1,
                        }}
                      >
                        {getFieldValue('picBackId') && getFieldValue('picBackId').length === 1
                          ? null
                          : uploadButton('上传证件反面')}
                      </OssUpload>
                    )}
                  </FormItem>
                </Col>
                <Col span={6}>
                  <UploadImageSample />
                </Col>
              </Col>
            </Row>
          </Form>
        </Modal>
      </>
    );
  }
}

export default Authentication;
